﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Service;

namespace WxImport
{
    public partial class Form1 : Form
    {
        static ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();
        GcGroupService groupService = new GcGroupService();
        GcGroupUserService groupUserService = new GcGroupUserService();
        private delegate void FlushClient(); //委托
        private delegate void ShowListBox(int n); //委托
        private delegate void ShowProgressBar(int n); //委托
        private int userCount = 0;
        private int currentCount = 0;

        public Form1()
        {
            InitializeComponent();
            List<FileInfo> list = GetFile();
            foreach (var item in list)
            {
                this.listBox1.Items.Add(item.Name);
                string json = File.ReadAllText(item.FullName, Encoding.Default);
                List<WxUser> userList = JsonConvert.DeserializeObject<List<WxUser>>(json);
                userCount += userList.Count;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.progressBar1.Value = 0;
            this.button1.Enabled = false;
            Thread thread = new Thread(DoWork);
            thread.Start();
        }

        private void DoWork()
        {
            try
            {
                ShowListBox sl = new ShowListBox(ShowItemFinish); //使用委托
                ShowProgressBar bar = new ShowProgressBar(ShowProgress);
                int i = 0;
                List<FileInfo> list = GetFile();
                foreach (var item in list)
                {
                    string json = File.ReadAllText(item.FullName, Encoding.Default);
                    List<WxUser> userList = JsonConvert.DeserializeObject<List<WxUser>>(json);
                    string fileName = Path.GetFileNameWithoutExtension(item.Name);
                    GcGroup groupInfo = groupService.GetInfoByName(fileName);
                   
                    if (groupInfo == null)
                    {
                        i++;
                        currentCount += userList.Count;
                        this.BeginInvoke(bar, currentCount);
                        continue;
                    }
                    QuitWxUser(userList, groupInfo.GroupID, fileName);
                    AddWxUser(userList, groupInfo.GroupID,bar);
                    this.BeginInvoke(sl, i);
                    i++;

                }
                FlushClient fc = new FlushClient(ButtonEnabled); //使用委托
                this.BeginInvoke(fc);
                
            }
            catch (Exception ex)
            {
                WirteLog(ex.Message + ex.StackTrace);
            }
         
        }

        private void ButtonEnabled()
        {
            this.button1.Enabled = true;
        }

        private void ShowItemFinish(int i)
        {
            this.listBox1.Items[i] += "  完成";
        }

        private void ShowProgress(int n)
        {
            this.progressBar1.Value = Convert.ToInt32(n*100 / userCount);
        }

        private List<FileInfo> GetFile()
        {
            List<FileInfo> list = new List<FileInfo>();
            string path = string.Format("{0}/wx", Application.StartupPath);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            DirectoryInfo di = new DirectoryInfo(path);
            //找到该目录下的文件 
            FileInfo[] fis = di.GetFiles();
            foreach (FileInfo fi in fis)
            {
                list.Add(fi);
               
            }
            return list;
        }

        private void AddWxUser(List<WxUser> list, int groupId, ShowProgressBar bar)
        {
            if (list.Count == 0)
            {
                return;
            }
            List<GcGroupUser> uList = groupUserService.GetListByGroupId(groupId);
            foreach (var info in list)
            {
                var ls = uList.Where(m => m.wxid == info.wxid).ToList();
                if (ls.Count >0 )
                {
                    var userInfo = ls[0];
                    bool isUpdate = false;
                    if (!string.IsNullOrWhiteSpace(info.head_img)&& userInfo.avatar != info.head_img)
                    {
                        isUpdate = true;
                        userInfo.avatar = info.head_img;
                    }
                    if (!string.IsNullOrWhiteSpace(info.nick_name)&& userInfo.nickname != info.nick_name)
                    {
                        isUpdate = true;
                        userInfo.nickname = info.nick_name;
                    }
                    if (!string.IsNullOrWhiteSpace(info.user_name)&&userInfo.wx_alias != info.user_name)
                    {
                        isUpdate = true;
                        userInfo.wx_alias = info.user_name;
                    }
                    if (isUpdate)
                    {
                        userInfo.UpdatedTime = DateTime.Now;
                        userInfo.QuitGroupTime = DateTime.MinValue;
                        groupUserService.Update(userInfo);
                    }
                }
                else
                {
                    GcGroupUser userInfo = new GcGroupUser
                    {
                        avatar = info.head_img,
                        nickname = info.nick_name,
                        CreatedTime = DateTime.Now,
                        GroupID = groupId,
                        IsDeleted = 0,
                        wx_alias = info.user_name,
                        wxid = info.wxid
                    };
                    groupUserService.Insert(userInfo);
                }
                currentCount++;
                this.BeginInvoke(bar, currentCount);
            }
        }

        /// <summary>
        /// 退群
        /// </summary>
        private void QuitWxUser(List<WxUser> userList, int groupId,string ownName)
        {
            List<int> intList = new List<int>();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            foreach (var item in userList)
            {
                if (!dic.ContainsKey(item.wxid))
                {
                    dic.Add(item.wxid, item.wxid);
                }
            }
           
            List<GcGroupUser> list = groupUserService.GetListByGroupId(groupId);
            foreach (var item in list)
            {
                if (item.nickname == ownName)
                {
                    continue;
                }
                if (!dic.ContainsKey(item.wxid))
                {
                    intList.Add(item.GroupUserID);
                }
            }
            groupUserService.SetQuitUserByIds(intList);
        }

        private void WirteLog(string msg)
        {
            try
            {
                string filePath = string.Format("{0}/err.txt", Application.StartupPath);
                LogWriteLock.EnterWriteLock();
                if (!File.Exists(filePath))
                {
                    File.Create(filePath).Close();
                }
                using (StreamWriter sw = new StreamWriter(filePath, true))
                {
                    sw.WriteLine(msg);
                    sw.Dispose();
                }
            }
            catch (FileNotFoundException fileCe)
            {
                throw fileCe;
            }
            catch (Exception ce)
            {
                throw ce;
            }
            finally
            {
                //退出写入模式，释放资源占用

                LogWriteLock.ExitWriteLock();
            }

        }

    }
}
